package com.example.testapp.activity.adapter;

import android.app.DatePickerDialog;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.RelativeSizeSpan;
import android.text.style.StyleSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.example.testapp.R;
import com.example.testapp.activity.dabastate.CalendarDao;
import com.example.testapp.activity.model.CalendarTag;
import com.example.testapp.activity.util.LunarCalendar;
import com.example.testapp.activity.util.SpecialCalendar;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

/**
 * Created by l on 2016/6/3.
 */
public class CalendarAdapter extends BaseAdapter {

    private CalendarDao dao = null;
    private boolean isLeapyear = false; //是否为闰年
    private int daysOfMonth = 0;  //某月的天数
    private int daysOfWeek = 0;  //具体某一天是星期几
    private int lastDaysOfMonth = 0; //上一个月的总天数
    private Context mContext;
    private String[] dayNumber = new String[49];  //一个gridview中的日期存入此数组中
    private static String week[] = {"周日","周一","周二","周三","周四","周五","周六"};
    private Resources res = null;
    private Drawable drawable = null;
    private SpecialCalendar sc = null;
    private LunarCalendar  lc = null;

    private String currentYear = "";
    private String currentMonth = "";
    private String currentDay = "";

    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-d");
    private int currentFlag = -1;     //用于标记当天
    private int[] schDateTagFlag = null;  //存储当月所有的日程日期

    private String showYear = "";   //用于在头部显示的年份
    private String showMonth = "";  //用于在头部显示的月份
    private String animalsYear = "";
    private String leapMonth = "";   //闰哪一个月
    private String cyclical = "";   //天干地支
    //系统当前时间
    private String sysDate = "";
    private String sys_year = "";
    private String sys_month = "";
    private String sys_day = "";

    //日程时间(需要标记的日程日期)
    private String sch_year = "";
    private String sch_month = "";
    private String sch_day = "";

    public CalendarAdapter(){
        Date date = new Date();
        sysDate = sdf.format(date);
        sys_year = sysDate.split("-")[0];
        sys_month=sysDate.split("-")[1];
        sys_day = sysDate.split("-")[2];
    }

    public CalendarAdapter(Context context, Resources rs, int jumpMonth, int jumpYear, int year_c, int month_c, int day_c) {
        this();
        this.mContext = context;
        this.res = rs;
        sc = new SpecialCalendar();
        lc = new LunarCalendar();
        int stepYear = year_c+jumpYear;
        int stepMonth =  month_c+jumpMonth ;

        if(stepMonth > 0){
            //往下一个月滑动
            if(stepMonth%12 == 0){
                stepYear = year_c + stepMonth/12 -1;
                stepMonth = 12;
            }else{
                stepYear = year_c + stepMonth/12;
                stepMonth = stepMonth%12;
            }
        }else{
            //往上一个月滑动
            stepYear = year_c-1 + stepMonth/12;
            stepMonth = stepMonth%12 + 12;
            if(stepMonth%12 == 0){
                /*stepYear = year_c + stepMonth/12 +1;
                stepMonth = 12;
            }else{
                stepYear = year_c + stepMonth/12;
                stepMonth = stepMonth%12;*/
            }
        }

        currentYear = String.valueOf(stepYear);
        currentMonth=String.valueOf(stepMonth);
        currentDay = String.valueOf(day_c);

        getCalendar(Integer.parseInt(currentYear), Integer.parseInt(currentMonth));
    }

    public CalendarAdapter(Context context, Resources resources, int year, int month, int day) {
        this();
        this.mContext = context;
        sc = new SpecialCalendar();
        lc = new LunarCalendar();
        this.res = resources;
        currentYear = String.valueOf(year);
        currentMonth = String.valueOf(month);
        currentDay = String.valueOf(day);

        getCalendar(Integer.parseInt(currentYear), Integer.parseInt(currentMonth));
    }

    @Override
    public int getCount() {
        return dayNumber.length;
    }

    @Override
    public Object getItem(int position) {
        return position;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder = null;
        if(convertView == null){
            viewHolder = new ViewHolder();
            convertView = LayoutInflater.from(mContext).inflate(R.layout.item_calendar, null);
            convertView.setTag(viewHolder);
        }else{
            viewHolder = (ViewHolder) convertView.getTag();
        }
        viewHolder.calTextView = (TextView) convertView.findViewById(R.id.calTV);
        String  d = dayNumber[position].split("\\.")[0];
        String  dv = dayNumber[position].split("\\.")[1];
        SpannableString sp = new SpannableString(d + "\n" + dv);
        sp.setSpan(new StyleSpan(Typeface.BOLD), 0, d.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        sp.setSpan(new RelativeSizeSpan(1.2f), 0, d.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        if(dv != null && dv != " "){
            sp.setSpan(new RelativeSizeSpan(0.75f), d.length()+1, dayNumber[position].length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        viewHolder.calTextView.setText(sp);
        viewHolder.calTextView.setTextColor(Color.GRAY);
        if(position<7){
            viewHolder.calTextView.setTextColor(Color.BLACK);
            drawable = res.getDrawable(R.mipmap.week_top);
            viewHolder.calTextView.setBackgroundDrawable(drawable);
        }
        if(position<daysOfMonth+daysOfWeek+7 && position >= daysOfWeek+7){
            viewHolder.calTextView.setTextColor(Color.BLACK);
            drawable = res.getDrawable(R.mipmap.item);
        }
        if(schDateTagFlag != null && schDateTagFlag.length > 0){
            for (int i=0; i< schDateTagFlag.length; i++){
                if(schDateTagFlag[i] == position){
                    viewHolder.calTextView.setBackgroundResource(R.mipmap.mark);
                }
            }
        }
        if(currentFlag == position){
           drawable = res.getDrawable(R.mipmap.current_day_bgc);
           viewHolder.calTextView.setBackgroundDrawable(drawable);
           viewHolder.calTextView.setTextColor(Color.WHITE);
        }
        return convertView;
    }

    /**
     * 在点击gridView时，得到这个月中最后一天的位置
     * @return
     */
    public int getEndPosition() {
        return (daysOfWeek + daysOfMonth + 7)-1;
    }

    /**
     * 在点击gridView时，得到这个月中第一天的位置
     * @return
     */
    public int getStartPosition() {
        return daysOfWeek + 7;
    }

    /**
     * 点击每一个item时返回item中的日期
     * @param position
     * @return
     */
    public String getDateByClickItem(int position) {
        return dayNumber[position];
    }

    public class ViewHolder{
        TextView calTextView;
    }

    //得到某年的某月的天数且这月的第一天是星期几
    private void getCalendar(int year, int month) {
         isLeapyear = sc.isLeapYear(year);
         daysOfMonth = sc.getDaysOfMonth(isLeapyear, month);
         daysOfWeek = sc.getWeekdayOfMonth(year, month);
         lastDaysOfMonth = sc.getDaysOfMonth(isLeapyear, month-1);
         Log.d("DAY", isLeapyear+" ======  "+daysOfMonth+"  ============  "+daysOfWeek+"  =========   "+lastDaysOfMonth);
         getWeek(year, month);
    }

    private void getWeek(int year, int month) {
        int j = 1;
        int flag = 0;
        String lunarDay = " ";

        //得到当前月的所有日程日期(这些日期需要标记)
        dao = new CalendarDao(mContext);
        ArrayList<CalendarTag> TagList = dao.getTagDate(year, month);
        if(TagList != null && TagList.size() > 0){
            schDateTagFlag = new int[TagList.size()];
        }
        for (int i = 0; i < dayNumber.length; i++){
            if(i < 7){
                dayNumber[i] = week[i] + "." + " ";
            }else if(i < daysOfWeek + 7){
                int temp = lastDaysOfMonth - daysOfWeek+1 - 7;
                lunarDay = lc.getLunarDate(year, month-1, temp+i, false);
                dayNumber[i] = (temp + i)+"."+lunarDay;
            }else if(i < daysOfMonth + daysOfWeek + 7){
                String day = String.valueOf(i - daysOfWeek + 1 - 7);
                lunarDay = lc.getLunarDate(year, month, i-daysOfWeek + 1 -7, false);
                dayNumber[i] = i - daysOfWeek + 1 -7 + "." + lunarDay;

                if (sys_year.equals(String.valueOf(year)) && sys_month.equals(String.valueOf(month)) && sys_day.equals(day)) {
                    currentFlag = i;
                }
                if(TagList != null && TagList.size() > 0){
                    for(int m = 0; m< TagList.size(); m++){
                        CalendarTag dateTag = TagList.get(m);
                        int matchYear = dateTag.getYear();
                        int matchMonth = dateTag.getMonth();
                        int matchDay = dateTag.getDay();
                        if(matchYear == year && matchMonth == month && matchDay == Integer.parseInt(day)){
                            schDateTagFlag[flag] = i;
                            flag++;
                        }
                    }
                }
                setShowYear(String.valueOf(year));
                setShowMonth(String.valueOf(month));
                setLeapMonth(lc.leapMonth == 0?"":String.valueOf(lc.leapMonth));
                setCyclical(lc.cyclical(year));
            }else{
                lunarDay = lc.getLunarDate(year, month+1, j, false);
                dayNumber[i] = j + "." + lunarDay;
                j++;
            }
        }

        String abc = " ";
        for(int i = 0; i < dayNumber.length; i++){
            abc = abc + dayNumber[i] + ":";
        }
        Log.d("DAYNUMBER",abc);
    }

    public String getCyclical() {
        return cyclical;
    }

    public void setCyclical(String cyclical) {
        this.cyclical = cyclical;
    }

    public String getShowMonth() {
        return showMonth;
    }

    public void setShowMonth(String showMonth) {
        this.showMonth = showMonth;
    }

    public String getShowYear() {
        return showYear;
    }

    public void setShowYear(String showYear) {
        this.showYear = showYear;
    }

    public String getLeapMonth() {
        return leapMonth;
    }

    public void setLeapMonth(String leapMonth) {
        this.leapMonth = leapMonth;
    }
}
